<template>
  <div>
    <div class="card">
      <el-input
        v-model="data.name"
        prefix-icon="Search"
        placeholder="请输入用户名"
        style="width: 300px; margin-right: 5px"
      >
        <template #prepend>用户名</template>
      </el-input>
      <el-button type="info" plain @click="load">查询</el-button>
      <el-button type="danger" plain @click="reset">重置</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBach">批量删除</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px">
      <el-table
        stripe
        :data="data.tableData"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="username" label="账号"></el-table-column>
        <el-table-column prop="avatar" label="头像">
          <!-- :src="scope.row.avatar"把链接回显成图片 -->
          <template v-slot="scope">
            <el-image
              style="
                width: 40px;
                height: 40px;
                border-radius: 50%;
                display: block;
              "
              v-if="scope.row.avatar"
              :src="scope.row.avatar"
              :preview-src-list="[scope.row.avatar]" 
              
              preview-teleported
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="phone" label="电话"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column fixed="right" label="操作" width="150">
          <!-- scope.row的意思是把当前行的数据带过去 -->
          <template v-slot="scope">
            <el-button
              type="primary"
              circle
              icon="Edit"
              @click="handleEdit(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              circle
              icon="Delete"
              @click="del(scope.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="card" v-if="data.total">
      <el-pagination
        @current-change="load"
        background
        layout="prev, pager, next"
        :page-size="data.pageSize"
        v-model:current-page="data.pageNum"
        :total="data.total"
      />
    </div>

    <!-- 新增表单 -->
    <el-dialog
      v-model="data.formVisible"
      title="管理员信息"
      width="40%"
      destory-on-close
    >
      <el-form ref="form" :model="data.form" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="data.form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-upload
            :action="baseUrl + '/files/upload'"
            :on-success="handleFileUpload"
            list-type="picture"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="data.form.name" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="data.form.phone" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="data.form.email" placeholder="请输入用户名" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取消</el-button>
          <el-button type="primary" @click="save"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import request from "@/utils/request";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref } from "vue";
import { reactive } from "vue";

const baseUrl = import.meta.env.VITE_BASE_URL;

const handleFileUpload = (res) => {
  data.form.avatar = res.data;
};

const data = reactive({
  // 控制对话框状态
  formVisible: false,
  // 表单
  form: {},
  tableData: [],
  total: 0,
  pageNum: 1,
  pageSize: 5,
  name: null,
  ids: [],
});

const load = () => {
  request
    .get("/admin/selectPage", {
      params: {
        // 分页查询
        pageNum: data.pageNum,
        pageSize: data.pageSize,
        name: data.name,
      },
    })
    .then((res) => {
      if (res.code === "200") {
        data.tableData = res.data?.list || [];
        data.total = res.data?.total;
      }
    });
};

const reset = () => {
  data.name = "";
  load();
};

/**
 * 编辑
 * @param row 当前行数据
 */
const handleEdit = (row) => {
  // 先转化成字符串再进行深拷贝 获取到这一行的数据是row 转化成Json 再赋值给data.form
  data.form = JSON.parse(JSON.stringify(row));
  data.formVisible = true;
};

/**
 * 删除
 */
const del = (id) => {
  ElMessageBox.confirm("删除后数据无法恢复，您确定删除吗？", "确认删除", {
    type: "warning",
  }).then(() => {
    request.delete("/admin/delete/" + id).then((res) => {
      if (res.code == "200") {
        ElMessage.success("删除成功");
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  });
};

/**
 * 批量删除
 */
const delBach = () => {
  if (!data.ids.length) {
    ElMessage.warning("请选择数据");
    return;
  }
  ElMessageBox.confirm("删除后数据无法恢复，您确定删除吗？", "删除确认", {
    type: "warning",
  })
    .then((res) => {
      request.delete("/admin/delete/batch", { data: data.ids }).then((res) => {
        if (res.code === "200") {
          ElMessage.success("操作成功");
          load();
        } else {
          ElMessage.error(res.msg);
        }
      });
    })
    .catch((err) => {
      console.error(err);
    });
};
const handleSelectionChange = (rows) => {
  // 提取rows里面的id 并将值赋值给data.ids
  data.ids = rows.map((v) => v.id);
};
const handleAdd = () => {
  // 清除数据
  data.form = {};
  data.formVisible = true;
  data.table = {};
};

const add = () => {
  // 调用后台接口直接把form数据传过去 然后判断状态码
  request.post("/admin/add", data.form).then((res) => {
    if (res.code == "200") {
      ElMessage.success("添加成功");
      data.formVisible = false;
      load();
    } else {
      // 提示错误
      ElMessage.error(res.msg);
    }
  });
};

const update = () => {
  // 更新要把data.form里面的数据传递给后端
  request.put("/admin/update", data.form).then((res) => {
    if (res.code == "200") {
      ElMessage.success("修改成功");
      data.formVisible = false;
      load();
    } else {
      // 提示错误
      ElMessage.error(res.msg);
    }
  });
};

// 新增和编辑 编辑不用填id
const save = () => {
  // 三元运算符 如果有id就是编辑 没有就是新增
  data.form.id ? update() : add();
};

load();
</script>

<style></style>
